<?php
/***************************************************************************
   Coppermine 1.3.1 for CPG-Dragonfly™
  **************************************************************************
   Port Copyright (c) 2004-2005 CPG Dev Team
   http://dragonflycms.com/
  **************************************************************************
   v1.1 (c) by Grégory Demar http://coppermine.sf.net/
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
****************************************************************************/
if (!defined('CPG_NUKE')) { exit; }
define('EDITPICS_PHP', true);
require("modules/{$module_name}/include/load.inc");
if (!GALLERY_ADMIN_MODE && !USER_ADMIN_MODE) { return cpg_die(_ERROR, ACCESS_DENIED); }

function process_post_data()
{
	global $db, $CONFIG, $user_albums_list;

	$user_album_set = array();
	foreach ($user_albums_list as $album) $user_album_set[$album['aid']] = 1;

	if (!$_POST->map('pics')) cpg_die(_CRITICAL_ERROR, PARAM_MISSING);

	foreach (array_keys($_POST['pics']) as $pid)
	{
		$pid = intval($pid);
		$aid = $_POST->uint('pics',$pid,'aid');

		$pic = $db->uFetchAssoc("SELECT category, filepath, filename
			FROM {$CONFIG['TABLE_PICTURES']} p, {$CONFIG['TABLE_ALBUMS']} a
			WHERE pid={$pid}
			  AND a.aid = p.aid");
		if (!$pic) { continue; }

		if (!GALLERY_ADMIN_MODE) {
			if ($pic['category'] != FIRST_USER_CAT + USER_ID) cpg_die(_ERROR, PERM_DENIED . "<br />(picture category = {$pic['category']}/ $pid)");
			if (!isset($user_album_set[$aid])) cpg_die(_ERROR, PERM_DENIED . "<br />(target album = $aid)");
		}

		$delete = in_array($pid, $_POST['delete']) || 'DELETE' === $_POST->txt('pics',$pid,'approved');

		if ($delete || in_array($pid, $_POST['del_comments'])) {
			$db->exec("DELETE FROM {$CONFIG['TABLE_COMMENTS']} WHERE pid={$pid}");
		}
		if ($delete)
		{
			$dir = $CONFIG['fullpath'];
			$file = $pic['filename'];
			if (!is_writable($dir)) cpg_die(_CRITICAL_ERROR, sprintf(DIRECTORY_RO, $dir));

			$files = array(
				$dir . $file,
				$dir . $CONFIG['normal_pfx'] . $file,
				$dir . $CONFIG['thumb_pfx'] . $file
			);
			foreach ($files as $currFile) {
				if (is_file($currFile)) unlink($currFile);
			}
			$db->exec("DELETE FROM {$CONFIG['TABLE_PICTURES']} WHERE pid={$pid}");
			continue;
		}

		$update = "aid={$aid}"
			.", title=".$db->quote($_POST->txt('pics',$pid,'title'))
			.", caption=".$db->quote(html2bb($_POST->raw('pics',$pid,'caption')))
			.", keywords=".$db->quote($_POST->txt('pics',$pid,'keywords'))
			.", user1=".$db->quote($_POST->txt('pics',$pid,'user1'))
			.", user2=".$db->quote($_POST->txt('pics',$pid,'user2'))
			.", user3=".$db->quote($_POST->txt('pics',$pid,'user3'))
			.", user4=".$db->quote($_POST->txt('pics',$pid,'user4'));
		if (UPLOAD_APPROVAL_MODE) {
			if ($_POST->bool('pics',$pid,'approved')) { $update .= ', approved=1'; }
		} else {
			if (in_array($pid, $_POST['reset_vcount'])) { $update .= ', hits=0'; }
			if (in_array($pid, $_POST['reset_votes']))  { $update .= ', pic_rating=0, votes=0'; }
		}
		$db->exec("UPDATE {$CONFIG['TABLE_PICTURES']} SET {$update} WHERE pid={$pid}");
	}
	speedup_pictures();
}

function get_user_albums($user_id)
{
	static $USER_ALBUMS_ARRAY = array(0 => array());
	if (!isset($USER_ALBUMS_ARRAY[$user_id])) {
		global $db, $CONFIG;
		$USER_ALBUMS_ARRAY[$user_id] = $db->uFetchAll("SELECT aid, title FROM {$CONFIG['TABLE_ALBUMS']} WHERE category='" . (FIRST_USER_CAT + $user_id) . "' ORDER BY title");
	}
	return $USER_ALBUMS_ARRAY[$user_id];
}

define('UPLOAD_APPROVAL_MODE', isset($_GET['mode']));

if (isset($album)) {
	$album_id = intval($album);
} else {
	$album_id = -1;
}

if (!UPLOAD_APPROVAL_MODE) {
	$ALBUM_DATA = $db->uFetchAssoc("SELECT title, category FROM {$CONFIG['TABLE_ALBUMS']} WHERE aid = {$album_id}");
	if (!$ALBUM_DATA) {
		return cpg_die(_CRITICAL_ERROR, NON_EXIST_AP);
	}
	$cat = $ALBUM_DATA['category'];
	if ($cat != FIRST_USER_CAT + USER_ID && !GALLERY_ADMIN_MODE) {
		return cpg_die(_ERROR, PERM_DENIED);
	}
}
else if (!GALLERY_ADMIN_MODE) {
	return cpg_die(_ERROR, ACCESS_DENIED);
}

$public_albums_list = GALLERY_ADMIN_MODE ? get_albumlist() : array();
$user_albums_list   = get_user_albums(USER_ID);

if (isset($_POST['save']))
{
	process_post_data();
	URL::redirect($_SERVER['REQUEST_URI']);
}

$start = isset($_GET['start']) ? (int)$_GET['start'] : 0;
$count = isset($_GET['count']) ? (int)$_GET['count'] : 25;
$s50   = $count ==  50 ? 'selected="selected"' : '';
$s75   = $count ==  75 ? 'selected="selected"' : '';
$s100  = $count == 100 ? 'selected="selected"' : '';

if (UPLOAD_APPROVAL_MODE) {
	$title = UPL_APPROVAL;
	$uri_mode = '&amp;mode=upload_approval';
	list($pic_count) = $db->uFetchRow("SELECT count(*) FROM {$CONFIG['TABLE_PICTURES']} WHERE approved=0");
	$result = $db->query("SELECT * FROM {$CONFIG['TABLE_PICTURES']} WHERE approved=0 ORDER BY pid LIMIT {$count} OFFSET {$start}");
} else {
	$title = EDIT_PICS;
	$uri_mode = '&amp;album='.$album_id;
	list($pic_count) = $db->uFetchRow("SELECT count(*) FROM {$CONFIG['TABLE_PICTURES']} WHERE aid={$album_id}");
	$result = $db->query("SELECT * FROM {$CONFIG['TABLE_PICTURES']} WHERE aid={$album_id} ORDER BY filename LIMIT {$count} OFFSET {$start}");
}

if (!$result->num_rows){
	$redirect = URL::index($module_name);
	pageheader(INFO, $redirect);
	msg_box(INFO, NO_MORE_IMAGES, CONTINU, $redirect);
	pagefooter();
	return;
}

$prev_link = $next_link = '';
if ($start + $count < $pic_count) {
	$next_target = URL::index('&amp;file=editpics'.$uri_mode.'&amp;start=' . ($start + $count) . '&amp;count=' . $count);
	$next_link = "<a href=\"$next_target\">".SEE_NEXT."</a> - ";
}
if ($start > 0) {
	$prev_target = URL::index('&amp;file=editpics'.$uri_mode.'&amp;start=' . max(0, $start - $count) . '&amp;count=' . $count);
	$prev_link = "<a href=\"$prev_target\">".SEE_PREV."</a> - ";
}

pageheader($title);

echo '
<script language="JavaScript">
function textCounter(field, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
	field.value = field.value.substring(0, maxlimit);
}
</script>
<form method="post" action="">
<table>
<thead>
	<tr>
		<th colspan="3">'.$title.'
			<div style="float:right">
				'.sprintf(N_PIC, $pic_count).' -
				'.$prev_link.'
				'.$next_link.'
				'.N_OF_PIC_TO_DISP.'
				<select onchange="location.href=\''.URL::index("&amp;file=editpics{$uri_mode}&amp;start={$start}&amp;count=%s").'\'.replace(\'%s\',this.currentOption().value);" name="count">
					<option value="25">25</option>
					<option value="50" '.$s50.'>50</option>
					<option value="75" '.$s75.'>75</option>
					<option value="100" '.$s100.'>100</option>
				</select>
			</div>
		</th>
	</tr>
</thead>
';

while ($CURRENT_PIC = $result->fetch_assoc())
{
	if (UPLOAD_APPROVAL_MODE) {
		$vf_row = $db->uFetchRow("SELECT username FROM " . $CONFIG['TABLE_USERS'] . " WHERE user_id='" . $CURRENT_PIC['owner_id'] . "'");
		$up_by = $vf_row[0];
		$up_by_link = '<a title="View Profile" href="'.URL::index('Your_Account&amp;profile=' . $CURRENT_PIC['owner_id']) . '" target="_blank">' .$up_by. '</a>';
		$up_by_edit_link = 'Edit User: <a title="Edit Profile" href="' .URL::index('&amp;file=usermgr&amp;opp=edit&amp;user_id=' . $CURRENT_PIC['owner_id']) . '" target="_blank">' .$up_by. '</a>';
		$pic_info = $CURRENT_PIC['pwidth'] . 'x' . $CURRENT_PIC['pheight'] . ' - ' . ($CURRENT_PIC['filesize'] >> 10) . $lang_byte_units[1].' Uploaded by: '.$up_by_link.' '.$up_by_edit_link;
	} else {
		$pic_info = sprintf(PIC_INFO_STR, $CURRENT_PIC['pwidth'], $CURRENT_PIC['pheight'], ($CURRENT_PIC['filesize'] >> 10), $CURRENT_PIC['hits'], $CURRENT_PIC['votes']);
	}
	$winsizeX = $CURRENT_PIC['pwidth']  + 16;
	$winsizeY = $CURRENT_PIC['pheight'] + 16;
	$thumb_url = get_pic_url($CURRENT_PIC, 'thumb');
	$filename = htmlprepare($CURRENT_PIC['filename']);
	$albums = $public_albums_list;
	if (GALLERY_ADMIN_MODE) {
		$albums += get_user_albums($CURRENT_PIC['owner_id']);
	}
//	foreach ($albums as &$album) { $album['selected'] = ($album['aid'] == $CURRENT_PIC['aid']); }
	echo '
	<tbody>
		<tr>
			<th colspan="2">'.$filename.'</th>
			<th style="text-align:center" rowspan="6">
				<a href="'.URL::index("&amp;file=displayimagepopup&amp;pid={$CURRENT_PIC['pid']}&amp;fullsize=1").'"
					target="'.uniqid(rand()).'"
					onClick="open(this.href,this.target,\'toolbar=yes,status=yes,resizable=yes,scrollbars=yes,width='.$winsizeX.',height='.$winsizeY.'\');return false"><img src="'.$thumb_url.'" alt=""/></a>
			</th>
		</tr>
		<tr>
			<td>'.PIC_INFO.'</td>
			<td>'.$pic_info.'</td>
		</tr>
		<tr>
			<td>'.ALBUM.'</td>
			<td>
				<select name="pics['.$CURRENT_PIC['pid'].'][aid]">
';
	foreach ($albums as $album) {
		echo '
					<option value="' . $album['aid'] . '"' . ($album['aid'] == $CURRENT_PIC['aid'] ? ' selected="selected"' : '') . '>' . $album['title'] . "</option>";
	}
	echo '
				</select>
			</td>
		</tr>
		<tr>
			<td>'.EDIT_TITLE.'</td>
			<td>
				<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][title]" maxlength="255" value="'.$CURRENT_PIC['title'].'"/>
			</td>
		</tr>
		<tr>
			<td valign="top">'.DESC.'</td>
			<td>
				<textarea name="pics['.$CURRENT_PIC['pid'].'][caption]" wrap="virtual" style="width: 100%;" maxlength="'.$CONFIG['max_img_desc_length'].'"
					onkeydown="textCounter(this, this.maxlength);" onkeyup="textCounter(this, this.maxlength);">'.$CURRENT_PIC['caption'].'</textarea>
			</td>
		</tr>
		<tr>
			<td>'.KEYWORDS.'</td>
			<td>
				<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][keywords]" maxlength="255" value="'.$CURRENT_PIC['keywords'].'"/>
			</td>
		</tr>
';
	if ($CONFIG['user_field1_name']) {
		echo '
			<tr>
				<td>'.$CONFIG['user_field1_name'].'</td>
				<td>
					<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][user1]" maxlength="255" value="'.$CURRENT_PIC['user1'].'"/>
				</td>
			</tr>
';
	}
	if ($CONFIG['user_field2_name']) {
		echo '
			<tr>
				<td>'.$CONFIG['user_field2_name'].'</td>
				<td>
					<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][user2]" maxlength="255" value="'.$CURRENT_PIC['user2'].'"/>
				</td>
			</tr>
';
	}
	if ($CONFIG['user_field3_name']) {
		echo '
			<tr>
				<td>'.$CONFIG['user_field3_name'].'</td>
				<td>
					<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][user3]" maxlength="255" value="'.$CURRENT_PIC['user3'].'"/>
				</td>
			</tr>
';
	}
	if ($CONFIG['user_field4_name']) {
		echo '
			<tr>
				<td>'.$CONFIG['user_field4_name'].'</td>
				<td>
					<input type="text" style="width: 100%" name="pics['.$CURRENT_PIC['pid'].'][user4]" maxlength="255" value="'.$CURRENT_PIC['user4'].'"/>
				</td>
			</tr>
';
	}

	if (UPLOAD_APPROVAL_MODE) {
		echo '
		<tr>
			<td colspan="3" align="center">
				<b><input type="radio" name="pics['.$CURRENT_PIC['pid'].'][approved]" value="1"/>'.APPROVE.'</b>
				<b><input type="radio" name="pics['.$CURRENT_PIC['pid'].'][approved]" value="0" checked="checked" />'.POSTPONE_APP.'</b>
				<b><input type="radio" name="pics['.$CURRENT_PIC['pid'].'][approved]" value="DELETE"/>'.DEL_PIC.'</b>
			</td>
		</tr>
';
	} else {
		echo '
		<tr>
			<td colspan="3" align="center">
				<b><input type="checkbox" name="delete[]" value="'.$CURRENT_PIC['pid'].'"/>'.DEL_PIC.'</b>
				<b><input type="checkbox" name="reset_vcount[]" value="'.$CURRENT_PIC['pid'].'"/>'.RESET_VIEW_COUNT.'</b>
				<b><input type="checkbox" name="reset_votes[]" value="'.$CURRENT_PIC['pid'].'"/>'.RESET_VOTES.'</b>
				<b><input type="checkbox" name="del_comments[]" value="'.$CURRENT_PIC['pid'].'"/>'.DEL_COMM.'</b>
			</td>
		</tr>
';
	}
	echo '</tbody>';
}
$result->free();

echo '
<tfoot>
	<tr>
		<td colspan="3"><button type="submit" name="save">'.APPLY.'</button></td>
	</tr>
</tfoot>
</table>
</form>';
pagefooter();
